package com.xc.hotelmgr.webapi.modules.op.service.impl;

import com.google.common.collect.Lists;
import com.xc.hotelmgr.webapi.common.utils.*;
import com.xc.hotelmgr.webapi.modules.dt.entity.StoreEntity;
import com.xc.hotelmgr.webapi.modules.dt.service.StoreService;
import com.xc.hotelmgr.webapi.modules.ht.entity.HtLogicRoomEntity;
import com.xc.hotelmgr.webapi.modules.ht.service.HtLogicRoomService;
import com.xc.hotelmgr.webapi.modules.mq.dto.DelRpMQ;
import com.xc.hotelmgr.webapi.modules.mq.dto.OpDtStoreGroup;
import com.xc.hotelmgr.webapi.modules.op.entity.*;
import com.xc.hotelmgr.webapi.modules.op.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import java.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xc.hotelmgr.webapi.modules.op.dao.HtlGroupDao;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service("htlGroupService")
@RequiredArgsConstructor
public class HtlGroupServiceImpl extends ServiceImpl<HtlGroupDao, HtlGroupEntity> implements HtlGroupService {

    private final RedisUtils redisUtils;

    private final DtUpHtlService dtUpHtlService;

    private final StoreService storeService;

    private final HtLogicRoomService htLogicRoomService;

    private final TaskStatusService taskStatusService;

    private final OurRateplanService ourRateplanService;

    private final SendMessageMgr sendMessageMgr;

    private static final String STORE_HOTEL_TASK_CODE = "STOREHOTEL";

    private static final String STORE_HOTEL_STATE_NAME = "自定义价格政策删除";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String dtId = (String) params.get("dtId");
        String pf = (String) params.get("pf");
        String storId = (String) params.get("storId");
        String groupId = (String) params.get("groupId");
        String inSql = "SELECT id FROM dt_dt WHERE FIND_IN_SET(id, getChild(" + dtId + "))";
        IPage<HtlGroupEntity> page = this.page(
                new Query<HtlGroupEntity>().getPage(params),
                new QueryWrapper<HtlGroupEntity>().eq(StringUtils.isNotBlank(pf), "blon_plantform", pf)
                        .eq(StringUtils.isNotBlank(storId), "store_id", storId)
                        .eq(StringUtils.isNotBlank(groupId), "group_id", groupId)
                        .inSql("dt_id", inSql)
        );
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public R saveHtlGroup(GroupDto groupDto) {
        String msg = "";
        List<HtlGroupEntity> htlGroupEntities = null;
        HtlGroupEntity htlGroupEntity = null;
        Long id = null;
        Integer storeId = Integer.valueOf(groupDto.getStorId());
        htlGroupEntities = Lists.newArrayList();
        List<DtUpHtlEntity> dtUpHtlEntities = new ArrayList<>();
        msg = "分组中添加或修改了" + groupDto.getHotelIds().length + "个酒店,可能需要一点时间。";
        List<Long> hotelIds = baseMapper.getHotelIdsByStoreId(storeId);
        for (String hid : groupDto.getHotelIds()) {
            if(!hotelIds.contains(Long.valueOf(hid))){
                htlGroupEntity = new HtlGroupEntity();
                htlGroupEntity.setDtId(Integer.valueOf(groupDto.getDtId()));
                htlGroupEntity.setStoreId(Integer.valueOf(groupDto.getStorId()));
                htlGroupEntity.setGroupId(groupDto.getId());
                htlGroupEntity.setGroupName(groupDto.getGroupName());
                htlGroupEntity.setHotelId(Long.valueOf(hid));
                htlGroupEntity.setBlonPlantform(Integer.valueOf(groupDto.getPf()));
                htlGroupEntity.setIsDel(0);
                //id = Long.valueOf(groupDto.getStorId() + groupDto.getId().toString() + hid);
                id = Long.valueOf((hid + groupDto.getStorId() + groupDto.getId().toString()));
                htlGroupEntity.setId(id);
                htlGroupEntities.add(htlGroupEntity);
            }
            DtUpHtlEntity dtUpHtlEntity = new DtUpHtlEntity();
            dtUpHtlEntity.setHotelId(Long.valueOf(hid));
            dtUpHtlEntity.setId(Long.valueOf(hid + groupDto.getStorId()));
            dtUpHtlEntity.setDtId(Integer.valueOf(groupDto.getDtId()));
            dtUpHtlEntity.setStatus(-1);
            dtUpHtlEntity.setStoreId(Integer.valueOf(groupDto.getStorId()));
            dtUpHtlEntities.add(dtUpHtlEntity);
        }
        return R.ok(msg).put("htl", htlGroupEntities).put("dthtl", dtUpHtlEntities);
    }

    @Override
    public PageUtils sqlQueryPage(Map<String, Object> params) {
        IPage<HtlGroupEntity> page = new Query<HtlGroupEntity>().getPage(params);
        params.put("page", page);
        List<HtlGroupEntity> list = baseMapper.sqlQueryPage(params);
        PageUtils pageUtils = new PageUtils(page, list);
        return pageUtils;
    }

    @Override
    public Long sqlQueryByGroupId(Integer id) {
        return baseMapper.sqlQueryByGroupId(id);
    }

    @Override
    public int queryOurRpCnt(Integer groupId) {
        return baseMapper.queryOurRpCnt(groupId);
    }

    @Override
    public List<Long> selectByGIdSId(Integer groupId, Integer storeId) {
        return baseMapper.selectByGIdSId(groupId, storeId);
    }

    @Override
    public List<HtlGroupEntity> selectByStoreId(Integer storeId) {
        return baseMapper.selectByStoreId(storeId);
    }

    @Override
    public boolean hotelInit(Integer groupId, Integer storeId, String redisK) {
        int status = -1;
        try {
            List<Long> hotelIdListS = dtUpHtlService.getHotelList(status);       // 查询系统所有上架的产品
            List<Long> hotelIdListG = baseMapper.getHotelList(groupId);    // 查询本分组产品

            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            Set<Object> set = new HashSet<>();  // 利用set相加去重
            set.addAll(hotelIdListG);
            set.addAll(hotelIdListS);
            if (!set.isEmpty()) {
                Object[] setL = set.toArray();
                redisUtils.sSet(uuid, setL);
            }
            Set<Object> hotelD = redisUtils.difference(redisK, uuid);
            Set<Object> hotelA = redisUtils.difference(uuid, redisK);
            if (!hotelD.isEmpty()) {
                Object[] hotelDel = hotelD.toArray();
                redisUtils.remove(redisK, hotelDel);
            }
            if (!hotelA.isEmpty()) {
                Object[] hotelAdd = hotelA.toArray();
                redisUtils.sSet(redisK, hotelAdd);
            }
            redisUtils.delete(uuid);
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    @Override
    public List<HtlGroupEntity> getOpHtlGroupHtLogicRoomByGIdAndSId(Integer groupId, Integer storeId) {

        return baseMapper.getOpHtlGroupHtLogicRoomByGIdAndSId(groupId, storeId);
    }

//    @Async
    @Override
    public void delHtlGroup(List<HtlGroupEntity> htlGroupEntitys) {
        if (htlGroupEntitys.size() <= 0) {
            return;
        }
        List delIds = Lists.newArrayList();
        Integer groupId = 0;
        int count = 0;

        // 执行酒店总数量
        Long num = Long.valueOf(htlGroupEntitys.size());
        Integer storeId = htlGroupEntitys.get(0).getStoreId();
        groupId = htlGroupEntitys.get(0).getGroupId();
        List<Integer> opOurRateplanIds = ourRateplanService.getByGroupId(groupId);
        StoreEntity dtStore = storeService.getById(storeId);
        String appKey = dtStore.getAppkey();

        // 生成新的任务
        TaskStatusEntity opTaskStatus = new TaskStatusEntity();
        opTaskStatus.setArchive(0);
        opTaskStatus.setTaskName(STORE_HOTEL_STATE_NAME);
        //完成数
        opTaskStatus.setCompPercent(0L);
        //总数
        opTaskStatus.setCompAmount(num);

        opTaskStatus.setStorId(storeId);
        opTaskStatus.setTaskCode(STORE_HOTEL_TASK_CODE);
        opTaskStatus.setStatus(0);
        opTaskStatus.setExcuTime(new Date());
        taskStatusService.save(opTaskStatus);
        Long taskId = opTaskStatus.getId();  // 任务id
        for (HtlGroupEntity htlGroupEntity : htlGroupEntitys) {
            Long hotelId = htlGroupEntity.getHotelId();
            List<HtLogicRoomEntity> htLogicRooms = htLogicRoomService.getByHotelId(hotelId);
            for(Integer opOurRateplanId : opOurRateplanIds) {
                for (HtLogicRoomEntity htLogicRoom : htLogicRooms) {
                    DelRpMQ delRpMQ = new DelRpMQ();
                    Long rpId = htLogicRoom.getId();
                    delRpMQ.setRpId(rpId);
                    delRpMQ.setTaskId(taskId);
                    delRpMQ.setOpOurRateplanId(opOurRateplanId);
                    sendMessageMgr.sendMessage(MqType.DELRP, delRpMQ, appKey);
                }
            }
            delIds.add(htlGroupEntity.getId());
        }
        DelRpMQ delRpMQ = new DelRpMQ();
        delRpMQ.setRpId((long) -1);
        sendMessageMgr.sendMessage(MqType.DELRP, delRpMQ, appKey);
        removeByIds(delIds);
    }

    @Override
    public List<OpDtStoreGroup> getStoreHotelByGroup(HtlGroupDto htlGroupDto) {

        return baseMapper.getStoreHotelByGroup(htlGroupDto);
    }

    @Override
    public List<Long> getHtlIdsByGroupId(Integer groupId) {
        return baseMapper.getHtlIdsByGroupId(groupId);
    }

    @Override
    public List<Long> getHotelIdsByStoreId(Integer storeId) {
        return baseMapper.getHotelIdsByStoreId(storeId);
    }
}
